package com.wlr.study.leetcode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author lerong.wang
 * @version 1.0.0
 * @description
 * @date 2024/12/26 19:53
 */
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "val=" + val +
                ", left=" + left +
                ", right=" + right +
                ", next=" + next +
                '}';
    }
};

public class LeetCode116 {
    public Node connect(Node root) {
        Node node = new Node();
        node.next = root;
        Deque<Node> que = new LinkedList<>();
        if (root == null) return node;
        que.offer(root);
        while (!que.isEmpty()) {
            int size = que.size();
            while (size > 0) {
                Node temp = que.poll();
                if (size == 1) {
                    temp.next = null;
                } else {
                    temp.next = que.peek();
                }
                if (temp.left != null) que.offer(temp.left);
                if (temp.right != null) que.offer(temp.right);
                size--;
            }

        }
        return root;
    }

    public static void main(String[] args) {
        LeetCode116 leetCode116 = new LeetCode116();
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        Node connect = leetCode116.connect(root);
        System.out.println(connect);

    }
}